﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Scheduler
{
    public class Scheduler
    {
        private readonly List<Worker> _workers = new List<Worker>();

        public Worker AddWorker(int st)
        {
            var worker = new Worker(st);
            _workers.Add(worker);
            return worker;
        }

        // 添加公用中间件，现在是添加到第一个 worker
        // TODO: 以后应该考虑另加一个名称为 "common" 的 worker
        public void AddCommandMiddleware(Middleware m)
        {
            _workers[0].AddMiddleware(m);
        }

        private void EmitEvent(Context context, EventArgs args)
        {
            foreach (var worker in _workers)
            {

                worker.EmitEvent(context, args);
            }
        }

        public Task Execute(Context context)
        {
            return Task.Run(() => DoExecute(context));
        }

        private void DoExecute(Context context)
        {
            EmitEvent(context, new EventArgs(EventId.Init));

            while (!context.UserCancelled)
            {
                EmitEvent(context, new EventArgs(EventId.PassBegin));
                if (context.UserCancelled) break;

                var tasks = _workers.Where(wk => !wk.ShouldSkipThisPass(context)).Select(w => w.Run(context)).ToArray();
                Task.WaitAll(tasks);
                EmitEvent(context, new EventArgs(EventId.PassEnd));
            }

            EmitEvent(context, new EventArgs(EventId.Cleanup));
        }
    }
}